<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="基于Vue.js的现代化待办事项管理应用" />
    <title>Vue属性绑定 - 待办事项管理</title>
    <script src="https://unpkg.com/vue@3.4.0"></script>
    <link rel="stylesheet" href="task-styles.css">
  </head>
  <body>
    <div id="app">
      <div class="container">
        <!-- 应用头部 -->
        <div class="app-header">
          <div class="header-left">
            <h1 class="app-title">你的代办事项</h1>
            <div class="user-greeting">
              <span class="greeting-text">
                报告主人！你还有
                <span class="highlight">{{pendingCount}}</span>
                个代办事项未完成，有
                <span class="highlight">{{completedCount}}</span>
                个已经过期了，有时间的话，赶紧去做吧。
              </span>
            </div>
          </div>
          <div class="header-right">
            <!-- 主题切换器 -->
            <div class="theme-switcher">
              <div class="theme-label">主题</div>
              <div class="theme-options">
                <button 
                  v-for="theme in themes" 
                  :key="theme.value"
                  @click="setTheme(theme.value)"
                  :class="['theme-btn', { 'active': currentTheme === theme.value }]"
                  :style="{ backgroundColor: theme.color }"
                  :title="theme.name"
                  :aria-label="`切换到${theme.name}`"
                >
                  {{theme.icon}}
                </button>
              </div>
            </div>
            <div class="user-avatar">
              <svg class="avatar-icon" viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"
                />
              </svg>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-section">
          <div class="input-group">
            <input
              type="text"
              v-model="newTask"
              placeholder="想计划写下来吗？"
              @keyup.enter="addTask"
              class="task-input"
              aria-label="输入新任务"
              maxlength="100"
            />
            <button 
              @click="addTask" 
              :disabled="!newTask.trim()" 
              class="add-btn"
              aria-label="添加新任务"
            >
              添加
            </button>
          </div>
          <div class="priority-section">
            <div class="priority-options">
              <label class="priority-option">
                <input type="radio" v-model="priority" value="重要" name="priority" aria-label="重要优先级" />
                <span class="priority-label">🔴 重要</span>
              </label>
              <label class="priority-option">
                <input type="radio" v-model="priority" value="一般" name="priority" aria-label="一般优先级" />
                <span class="priority-label">🔵 一般</span>
              </label>
              <label class="priority-option">
                <input type="radio" v-model="priority" value="低" name="priority" aria-label="低优先级" />
                <span class="priority-label">⚪ 低</span>
              </label>
            </div>
            <div class="priority-display" aria-live="polite">当前优先级：{{priority}}</div>
          </div>
        </div>

        <div class="task-list-header">
          <h3>任务列表</h3>
        </div>

        <!-- 任务列表 -->
        <div class="task-list">
          <div v-if="filteredTasks.length === 0" class="empty-state" role="status">
            <div class="empty-icon">📋</div>
            <p class="empty-text">还没有任务，开始添加第一个任务吧！</p>
          </div>

          <div
            v-for="task in filteredTasks"
            :key="task.id"
            :class="['task-item', { 'completed': task.completed, 'priority-high': task.priority === '重要' }]"
            class="task-item"
            role="listitem"
            :aria-label="`任务: ${task.text}, 优先级: ${task.priority}, ${task.completed ? '已完成' : '未完成'}`"
          >
            <!-- 编辑模式 -->
            <div v-if="editingTask === task.id" class="task-content">
              <button 
                class="task-priority-indicator" 
                :class="'priority-' + task.priority"
                @click="toggleTask(task.id)"
                :aria-label="task.completed ? '标记为未完成' : '标记为已完成'"
                :title="task.completed ? '点击标记为未完成' : '点击标记为已完成'"
              >
                {{getPriorityIcon(task.priority)}}
              </button>
              <div class="task-info" style="flex: 1;">
                <input 
                  v-model="editText" 
                  class="edit-input"
                  @keyup.enter="saveEdit"
                  @keyup.escape="cancelEdit"
                  :aria-label="'编辑任务文本'"
                  maxlength="100"
                  autofocus
                />
                <div class="task-meta">
                  <span class="task-priority">{{task.priority}}</span>
                  <span class="task-date">{{formatDate(task.createdAt)}}</span>
                </div>
                <div class="edit-actions">
                  <button 
                    class="action-btn save-btn" 
                    @click="saveEdit"
                    :disabled="!editText.trim()"
                    :aria-label="'保存编辑'"
                  >
                    ✅ 保存
                  </button>
                  <button 
                    class="action-btn cancel-btn" 
                    @click="cancelEdit"
                    :aria-label="'取消编辑'"
                  >
                    ❌ 取消
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 普通显示模式 -->
            <div v-else class="task-content">
              <button 
                class="task-priority-indicator" 
                :class="'priority-' + task.priority"
                @click="toggleTask(task.id)"
                :aria-label="task.completed ? '标记为未完成' : '标记为已完成'"
                :title="task.completed ? '点击标记为未完成' : '点击标记为已完成'"
              >
                {{getPriorityIcon(task.priority)}}
              </button>
              <div class="task-info">
                <div class="task-text" :class="{ 'completed-text': task.completed }">
                  {{task.text}}
                </div>
                <div class="task-meta">
                  <span class="task-priority">{{task.priority}}</span>
                  <span class="task-date">{{formatDate(task.createdAt)}}</span>
                </div>
              </div>
              <div class="task-actions">
                <button 
                  class="action-btn edit-btn" 
                  @click="editTask(task.id)"
                  :aria-label="`编辑任务: ${task.text}`"
                >
                  ✏️ 编辑
                </button>
                <button 
                  class="action-btn delete-btn" 
                  @click="removeTask(task.id)"
                  :aria-label="`删除任务: ${task.text}`"
                >
                  🗑️ 删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script>
      const { createApp, ref, computed, watch, onMounted } = Vue

      const App = {
        setup() {
          // 基础数据
          const newTask = ref('')
          const priority = ref('一般')
          const tasks = ref([])
          const currentFilter = ref('all')
          const editingTask = ref(null)
          const editText = ref('')

          let nextId = 1

          // 主题相关
          const currentTheme = ref('dark-theme')
          const themes = ref([
            { value: 'dark-theme', name: '深色主题', icon: '🌙', color: '#2d3748' },
            { value: 'light-theme', name: '浅色主题', icon: '☀️', color: '#f7fafc' },
            { value: 'blue-theme', name: '蓝色主题', icon: '🌊', color: '#3182ce' },
            { value: 'green-theme', name: '绿色主题', icon: '🌿', color: '#38a169' }
          ])

          // 计算属性
          const completedCount = computed(() => {
            return tasks.value.filter(task => task.completed).length
          })

          const pendingCount = computed(() => {
            return tasks.value.filter(task => !task.completed).length
          })

          const filteredTasks = computed(() => {
            let filtered = tasks.value

            if (currentFilter.value === 'pending') {
              filtered = filtered.filter(task => !task.completed)
            } else if (currentFilter.value === 'completed') {
              filtered = filtered.filter(task => task.completed)
            }

            return filtered
          })

          // 方法
          const addTask = () => {
            const taskText = newTask.value.trim()
            if (taskText === '' || taskText.length > 100) return

            tasks.value.push({
              id: nextId++,
              text: taskText,
              priority: priority.value,
              completed: false,
              createdAt: new Date().toLocaleString()
            })

            newTask.value = ''
            // 保存到本地存储
            saveToLocalStorage()
          }

          const toggleTask = (id) => {
            const task = tasks.value.find(task => task.id === id)
            if (task) {
              task.completed = !task.completed
              saveToLocalStorage()
            }
          }

          const editTask = taskId => {
            const task = tasks.value.find(t => t.id === taskId)
            if (task) {
              editingTask.value = taskId
              editText.value = task.text
            }
          }

          const saveEdit = () => {
            if (editText.value.trim() && editingTask.value) {
              const task = tasks.value.find(task => task.id === editingTask.value)
              if (task) {
                task.text = editText.value.trim()
                editingTask.value = null
                editText.value = ''
                saveToLocalStorage()
              }
            }
          }

          const cancelEdit = () => {
            editingTask.value = null
            editText.value = ''
          }

          const removeTask = taskId => {
            if (confirm('确定要删除这个任务吗？')) {
              const index = tasks.value.findIndex(t => t.id === taskId)
              if (index > -1) {
                tasks.value.splice(index, 1)
                saveToLocalStorage()
              }
            }
          }

          const getPriorityIcon = (priority) => {
            const icons = {
              '重要': '🔴',
              '一般': '🔵',
              '低': '⚪'
            }
            return icons[priority] || '⚪'
          }

          const formatDate = (date) => {
            if (!date) return ''
            const now = new Date()
            const taskDate = new Date(date)
            const diffTime = now - taskDate
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
            
            if (diffDays === 0) return '今天'
            if (diffDays === 1) return '昨天'
            if (diffDays < 7) return `${diffDays}天前`
            return taskDate.toLocaleDateString('zh-CN')
          }

          const saveToLocalStorage = () => {
            try {
              localStorage.setItem('vue-tasks', JSON.stringify(tasks.value))
            } catch (error) {
              console.warn('无法保存到本地存储:', error)
            }
          }

          const loadFromLocalStorage = () => {
            try {
              const saved = localStorage.getItem('vue-tasks')
              if (saved) {
                const parsedTasks = JSON.parse(saved)
                // 确保日期对象正确解析
                parsedTasks.forEach(task => {
                  if (task.createdAt) {
                    task.createdAt = new Date(task.createdAt)
                  }
                })
                tasks.value = parsedTasks
                // 更新nextId
                const maxId = Math.max(...parsedTasks.map(t => t.id), 0)
                nextId = maxId + 1
              }
            } catch (error) {
              console.warn('无法从本地存储加载:', error)
            }
          }

          // 主题切换方法
          const setTheme = (theme) => {
            currentTheme.value = theme
            document.body.className = theme
            localStorage.setItem('vue-theme', theme)
          }

          const loadTheme = () => {
            const savedTheme = localStorage.getItem('vue-theme')
            if (savedTheme) {
              currentTheme.value = savedTheme
              document.body.className = savedTheme
            } else {
              document.body.className = currentTheme.value
            }
          }

          // 初始化示例数据
          if (tasks.value.length === 0) {
            tasks.value = [
              {
                id: nextId++,
                text: '学习前端基础HTML5/CSS3/JavaScript',
                priority: '重要',
                completed: true,
                createdAt: new Date('2024-01-15').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习Vue.JS的基础知识',
                priority: '重要',
                completed: false,
                createdAt: new Date('2024-01-14').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习前端构建工具',
                priority: '重要',
                completed: true,
                createdAt: new Date('2024-01-16').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习前端UI构建',
                priority: '重要',
                completed: false,
                createdAt: new Date('2024-01-13').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习前端状态管理',
                priority: '重要',
                completed: true,
                createdAt: new Date('2024-01-12').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习前端路由管理',
                priority: '重要',
                completed: true,
                createdAt: new Date('2024-01-17').toLocaleString()
              },
              {
                id: nextId++,
                text: '学习前端网络管理',
                priority: '低',
                completed: false,
                createdAt: new Date('2024-01-11').toLocaleString()
              },
              {
                id: nextId++,
                text: '综合案例实战',
                priority: '重要',
                completed: true,
                createdAt: new Date('2024-01-18').toLocaleString()
              }
            ]
          }

          // 组件挂载时加载数据
          onMounted(() => {
            loadFromLocalStorage()
            loadTheme()
          })

          // 监听任务变化，自动保存
          watch(tasks, () => {
            saveToLocalStorage()
          }, { deep: true })

          return {
            newTask,
            priority,
            tasks,
            currentFilter,
            completedCount,
            pendingCount,
            filteredTasks,
            editingTask,
            editText,
            currentTheme,
            themes,
            addTask,
            toggleTask,
            editTask,
            saveEdit,
            cancelEdit,
            removeTask,
            getPriorityIcon,
            formatDate,
            saveToLocalStorage,
            loadFromLocalStorage,
            setTheme
          }
        }
      }

      createApp(App).mount('#app')
    </script>
  </body>
</html>
